//
//  ViewController.m
//  CIMKit
//
//  Created by mason on 2020/11/7.
//

#import "ViewController.h"
#import "SocketRocket.h"

#import "GCDAsyncSocket.h"
#import "SentBody.pbobjc.h"
#import "Message.pbobjc.h"
#import "NSData+IM.h"
#import "NSString+IM.h"
#import "CIMHeader.h"
#import "AViewController.h"

@interface ViewController ()<GCDAsyncSocketDelegate,CIMPeerMessageObserver,CIMConnectionObserver>

@property (strong, nonatomic) SRWebSocket *imWebSocket;
@property (strong, nonatomic) GCDAsyncSocket * clientSocket;


@end

@implementation ViewController




- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self presentViewController:[AViewController new] animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColor.redColor;

    [[CIMService instance] configHost:@"192.168.51.197" onPort:23456];

    [[CIMService instance] connectionBindUserId:@"111111"];

    [[CIMService instance] addMessageObserver:self];
    [[CIMService instance] addConnectionObserver:self];

    return;


    _clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //连接服务器
    NSError *error;
    [_clientSocket connectToHost:@"192.168.51.197" onPort:23456 error:&error];
    if (error) {
        NSLog(@"socket 连接失败");
    }else{
        NSLog(@"socket 成功");
        SentBodyModel * body = [SentBodyModel new];

        body.key = @"client_bind";
        body.timestamp = (int64_t)[NSDate timeIntervalSinceReferenceDate] *1000;
        body.data_p[@"account"] = @"1111111222";
        body.data_p[@"deviceId"] = @"1221211";
        body.data_p[@"channel"] = @"ios";

        NSData *modeData = body.data;

        NSInteger lenght = modeData.length;

        Byte type = 3;

        Byte head[3] ;

        head[0] = type;
        head[1] = lenght & 0xff;
        head[2] = (lenght >> 8) & 0xff;

        NSMutableData * sendData = [[NSMutableData alloc] initWithBytes:head length:3];

        [sendData appendData:modeData];

        [_clientSocket writeData:[CIMSendMessageData initBindUserData:@"111111"] withTimeout:-1 tag:0];
        
    }


}

- (void)cimDidConnectClose{
    NSLog(@"cimDidConnectClose");

}

- (void)cimDidConnectError:(NSError *)error{
    NSLog(@"cimDidConnectError");

}

- (void)cimDidConnectSuccess{
    NSLog(@"cimDidConnectSuccess");

}

- (void)cimDidBindUserSuccess:(BOOL)bindSuccess{
    NSLog(@"cimDidBindUserSuccess");
}

- (void)cimHandleMessage:(CIMMessageModel *)msg{
    NSLog(@"ViewController:%@\nu用户：%@(%lld)\n---------",msg.content,msg.sender,msg.timestamp);
}
- (void)cimHandleMessageError:(NSData *)data{
    NSLog(@"cimHandleMessageError");
}


#pragma mark - GCDAsyncSocketDelegate

// 连接成功
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
   NSLog(@"socket 连接成功");
   // 读取数据，必须添加，相当于主动添加一个读取请求，不然不会执行读取信息回调方法
   [_clientSocket readDataWithTimeout:-1 tag:0];

}

// 已经断开链接
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
   NSLog(@"socket 断开连接%@",err.localizedDescription);

}

//读取到数据
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

   [_clientSocket readDataWithTimeout:-1 tag:0];

    NSData *head = [data subdataWithRange:NSMakeRange(0, 3)];//取得头部数据
    NSData * tagData = [head subdataWithRange:NSMakeRange(0, 1)];
    NSString* hexString = [tagData convertDataToHexStr];

    if([hexString isEqual:@"01"]){

        NSData * model = [@"CR" convertBytesStringToData];

        NSInteger lenght = model.length;

        Byte type = 0;

        Byte head[3] ;

        head[0] = type;
        head[1] = lenght & 0xff;
        head[2] = (lenght >> 8) & 0xff;

        NSMutableData * sendData = [[NSMutableData alloc] initWithBytes:head length:3];

        [sendData appendData:model];

        [_clientSocket writeData:sendData withTimeout:-1 tag:0];
    }

    if([hexString isEqual:@"02"]){

        NSData * lv = [data subdataWithRange:NSMakeRange(1, 1)];
        NSData * hv = [data subdataWithRange:NSMakeRange(2, 1)];

        NSString * lvString  = [[lv convertDataToHexStr] hexToDecimal];
        NSString * hvString  = [[hv convertDataToHexStr] hexToDecimal];
        
        NSLog(@"--hexHeight--%@",hvString);

        NSData * messageData = [data subdataWithRange:NSMakeRange(3, lvString.intValue)];

        NSError * error;

        MessageModel * messgae = [[MessageModel alloc] initWithData:messageData error:&error];

        NSLog(@"02:didReadData-----%@",messgae.content);

    }

    NSLog(@"didReadData----%@",hexString);
}






@end
